package com.gxa.admin.oss.service.impl;

import com.gxa.admin.oss.config.StorageConfig;
import com.gxa.admin.oss.service.AbstractStorageService;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;

import java.io.File;
import java.util.Random;

/**
 * <h3>travel</h3>
 * <p></p>
 *
 * @author : ch
 * @date : 2024-03-11 20:46
 **/

public class TencentStorageService extends AbstractStorageService {

    private COSCredentials cosCredentials;

    private ClientConfig clientConfig;

    public TencentStorageService(StorageConfig storageConfig) {
        this.storageConfig = storageConfig;
        init();
    }

    public void init(){
        this.cosCredentials=new BasicCOSCredentials(
                this.storageConfig.getTencentSecretId(),
                this.storageConfig.getTencentSecretKey());
        this.clientConfig=new ClientConfig(new Region("ap-chengdu"));
    }

    //返回值是    能访问图片地址
    @Override
    public String uploadFile(File localFile) {

        COSClient cosClient=new COSClient(cosCredentials,clientConfig);

        String fileName="";

        try{
            fileName=localFile.getName();

            String subsring=fileName.substring(fileName.lastIndexOf("."));

            Random random=new Random();

            fileName=storageConfig.getTencentPrefix()+"/"+random.nextInt(10000)+System.currentTimeMillis()+subsring;
            PutObjectRequest putObjectRequest=new PutObjectRequest(this.storageConfig.getTencentBucketName(),fileName,localFile);
            PutObjectResult putObjectResult=cosClient.putObject(putObjectRequest);

        }catch (Exception e){
            e.printStackTrace();
        }
        finally {
            cosClient.shutdown();
        }

        return this.storageConfig.getTencentUrl()+fileName;
    }
}
